<?php
require_once("user.php");
require_once("managedocument.php");

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["datafile"]["name"]);
$uploadOk = true;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);

if(isset($_POST["action"])) {
	
	$key ="user";
	$user=null;
	if(session_id() == '') {
		session_start();
	}
	$key = "user";
	$user = unserialize ( $_SESSION [$key] );
	$unitId=$user->getUnitId();
	$userId=$user->getUserId();
	
	// Check if file already exists
	if (file_exists($target_file)) {
		echo '{"status" :"faiure","message":"Sorry, file already exists."}';
		$uploadOk = false;
	}
	if($uploadOk){
		// Check file size
		if ($_FILES["datafile"]["size"] > 500000) {
			echo '{"status" :"faiure","message":"Sorry, your file is too large."}';
			$uploadOk = false;
		}
	}
	if($uploadOk){
		// Allow certain file formats
		if($fileType != "doc" && $fileType != "txt" && $fileType != "pdf") {
			echo '{"status" :"faiure","message":"Sorry, only DOC, TXT  PDF files are allowed."}';
			$uploadOk = false;
		}
	}
	// Check if $uploadOk is set to 0 by an error
	if ($uploadOk ) {
		if (move_uploaded_file ( $_FILES ["datafile"] ["tmp_name"], $target_file )) {
			$documentManager=new ManageDocuments();
			$filesize=$_FILES ["datafile"]["size"] ;
			$fileName=$_FILES["datafile"]["name"];
			$url="lib/" .$target_file;
			if($user->isActionAllowed("CAN_ADD_DOCUMENT_FOR_OTHERS","GLOBAL")){
				$unitId=$_POST["unit_select"];
			}
			$status=$documentManager->addDocument($fileName,$filesize,$url,$userId,$unitId);
			
			echo '{"status" :"success","message":"The file has been uploaded."}';
		} else {
			echo '{"status" :"faiure","message":"Sorry, there was an error uploading your file."}';
		}
	}
}
		
?>